package com.xdcplus.web.service.report.impl;

import cn.hutool.core.util.StrUtil;
import com.xdcplus.mom.pojo.vo.DeviceFixRecordVO;
import com.xdcplus.mom.pojo.vo.DevicePmRecordVO;
import com.xdcplus.mom.utils.GuidConverter;
import com.xdcplus.web.common.pojo.vo.device.EpmUserVO;
import com.xdcplus.web.mapper.device.DevicePerformanceMapper;
import com.xdcplus.web.service.report.EpmStatusBoardDataService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author Zhecheng.Ren
 * @since 2024/9/30 11:23
 */
@Service("epmStatusBoardDataService")
public class EpmStatusBoardDataServiceImpl implements EpmStatusBoardDataService {

    @Resource
    private DevicePerformanceMapper devicePerformanceMapper;

    private static final DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    @Override
    public List<DevicePmRecordVO> queryPmRecord(String startDate, String endDate) {
        List<DevicePmRecordVO> devicePmRecordVOS = devicePerformanceMapper.queryPmRecord(startDate, endDate);
        List<EpmUserVO> epmUserVOS = devicePerformanceMapper.queryUserList();
        devicePmRecordVOS.forEach(devicePmRecordVO -> {
            String pmDate = devicePmRecordVO.getPmDate();
            LocalDateTime startTime = LocalDateTime.parse(pmDate, df);
            devicePmRecordVO.setKeepTime(calculateKeepTime(startTime, LocalDateTime.now()));
            for (EpmUserVO epmUserVO : epmUserVOS) {
                if (StrUtil.isNotBlank(devicePmRecordVO.getPmUser()) && devicePmRecordVO.getPmUser().equals(GuidConverter.convertGuid(epmUserVO.getId()))) {
                    devicePmRecordVO.setPmUser(epmUserVO.getUserName());
                }
            }
        });
        return devicePmRecordVOS;
    }

    @Override
    public List<DeviceFixRecordVO> queryFixRecord(String startDate, String endDate) {
        LocalDateTime localDateTime = LocalDateTime.now();
        List<DeviceFixRecordVO> deviceFixRecordVOS = devicePerformanceMapper.queryFixRecord(startDate, endDate);
        deviceFixRecordVOS.forEach(deviceFixRecordVO -> {
            String fixTime = deviceFixRecordVO.getFixTime();
            LocalDateTime startTime = LocalDateTime.parse(fixTime, df);
            deviceFixRecordVO.setKeepTime(calculateKeepTime(startTime, localDateTime));
        });
        return deviceFixRecordVOS;
    }

    private String calculateKeepTime(LocalDateTime startTime, LocalDateTime endTime) {

        // 计算两个时间点的差值
        Duration duration = Duration.between(startTime, endTime);

        // 获取相差的总秒数
        long seconds = duration.getSeconds();

        double minutes = (double) seconds / 60.0;

        // 使用DecimalFormat来格式化输出结果，保留两位小数
        DecimalFormat df = new DecimalFormat("#.00");

        return df.format(minutes);
    }
}
